package com.example.administrator.smartdevice.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.administrator.smartdevice.R;
import com.example.administrator.smartdevice.activity.LoginActivity;
import com.example.administrator.smartdevice.event.AskListEvent;
import com.example.administrator.smartdevice.event.MessageEvent;
import com.example.administrator.smartdevice.model.ApplianceModel;
import com.example.administrator.smartdevice.net.HttpUtils;
import com.example.administrator.smartdevice.net.RequestCallback;
import com.example.administrator.smartdevice.utils.AgentConstants;
import com.example.administrator.smartdevice.utils.AgentSharedPreferences;
import com.example.administrator.smartdevice.utils.AppApplication;
import com.example.administrator.smartdevice.utils.ServerConstants;
import com.example.administrator.smartdevice.utils.UUIDUtil;
import com.example.administrator.smartdevice.widget.CustomDialog;
import com.example.administrator.smartdevice.widget.CustomTipDialog;
import com.hhc.netty.DeviceModel;
import com.hhc.netty.NettyClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity implements RequestCallback {
    protected BaseActivity mBaseActivity = null;
    protected CustomTipDialog tipDialog;//加载对话框
    protected MessageEvent messageEvent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBaseActivity = this;
        setContentView();
        ButterKnife.bind(this);
        AppApplication.add(this);
        initData();
    }

    /**
     * 设置布局
     */
    protected abstract void setContentView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 页面跳转
     */
    protected void startOtherActivity(Class<?> className, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, className);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected void startOtherActivityForResult(Class<?> className, Bundle bundle,
                                               int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, className);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 弹出消息
     */
    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int msgID) {
        Toast.makeText(this, msgID, Toast.LENGTH_SHORT).show();
    }

    /**
     * 弹出对话框
     */
    protected void showInformationDialog(String message, int which1, int which2,
                                         DialogInterface.OnClickListener onClickListener) {
        new CustomDialog.Builder(this)
                .setTitle("智能家居")
                .setMessage(message)
                .setButton(which1, "确定", onClickListener)
                .setButton(which2, "取消", onClickListener)
                .setCancelable(false)
                .create()
                .show();
    }

    /**
     * 弹出提示对话框
     * canceable: back键可以取消：true
     * 不可以取消：false
     */
    protected void startTipDialog(int iconType, String message, boolean cancelable) {
        if (tipDialog == null) {
            tipDialog = new CustomTipDialog(this);
            tipDialog.setIconType(iconType);
            tipDialog.setMessage(message);
            tipDialog.setCanceledOnTouchOutside(false);
            tipDialog.setCancelable(cancelable);
        }
        tipDialog.show();
    }

    /**
     * 销毁加载对话框
     */
    protected void stopTipDialog() {
        if (tipDialog != null) {
            tipDialog.dismiss();
        }
        tipDialog = null;
    }

    //公共标题处理
    protected void configCommonHeader(final Activity activity, String title, boolean visibility) {
        RelativeLayout header = (RelativeLayout) activity.findViewById(R.id.common_head);
        TextView titleTV = (TextView) header.findViewById(R.id.common_head_title);
        titleTV.setText(title);
        ImageView back = (ImageView) findViewById(R.id.common_head_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ImageView more = (ImageView) header.findViewById(R.id.common_head_more);
        if (visibility) {
            more.setVisibility(View.VISIBLE);
        } else {
            more.setVisibility(View.GONE);
        }
    }

    protected abstract void onFailure(int requestCode, Object object);

    protected abstract void onSuccess(int requestCode, Object object);

    @Override
    public void onSuccessCallback(int requestCode, Object object) {
        onSuccess(requestCode, object);
        if (requestCode == 5001) {
            if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                ApplianceModel applianceModel = (ApplianceModel) HttpUtils.getData(object, ApplianceModel.class);
                //1.存在,本地的状态list更新，同时发送上线通知
                //10:上线 20：下线
                if (messageEvent.getOperationType().equals("10")) {
                    DeviceModel deviceModel = new DeviceModel();
                    //基本项：device_id和appliance_id
                    deviceModel.setDeviceId(AgentSharedPreferences.getMemberInfo(this).getMemberDeviceId());
                    deviceModel.setApplianceId(messageEvent.getApplianceId());
                    //家电上线状态:上线
                    deviceModel.setOnlineStatus("10");
                    //家电开关状态：关
                    deviceModel.setStatus("20");
                    NettyClient.getInstance().deviceOnline(deviceModel);
                    //生成上线信息
                    createOnlineMessage(applianceModel.getMasterId(), applianceModel.getApplianceId(), "10");
                } else if (messageEvent.getOperationType().equals("20")) {
                    DeviceModel deviceModel = new DeviceModel();
                    //基本项：device_id和appliance_id
                    deviceModel.setDeviceId(AgentSharedPreferences.getMemberInfo(this).getMemberDeviceId());
                    deviceModel.setApplianceId(messageEvent.getApplianceId());
                    //家电上线状态：下线
                    deviceModel.setOnlineStatus("20");
                    //家电开关状态：关
                    deviceModel.setStatus("20");
                    //本地存设备状态->用到场景：移动端请求获取设备状态
                    NettyClient.getInstance().deviceOffline(deviceModel);
                    //生成上线信息
                    createOnlineMessage(applianceModel.getMasterId(), applianceModel.getApplianceId(), "20");
                }
            } else {
                //2.不存在，直接放到请求列表，即是请求加入
                NettyClient.getInstance().addDevice(messageEvent);
                //如果当前界面就是请求加入界面，更新
                EventBus.getDefault().post(new AskListEvent());
            }
        }
    }

    @Override
    public void onFailureCallback(int requestCode, Object object) {
        onFailure(requestCode, object);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {

        AppApplication.remove(this);
        stopTipDialog();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (tipDialog != null)
            tipDialog = null;
    }

    public void exit() {
        Intent intent = new Intent();
        intent.setClass(mBaseActivity, LoginActivity.class);
        intent.setAction(AgentConstants.Action.EXIT_APP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    //设备是否被添加了
    public void isExist(String applianceId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("applianceId", applianceId);
        HttpUtils.post(mBaseActivity, 5001, ServerConstants.IS__APPLIANCE_EXIST, jsonObject.toString(), this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent messageEvent) {
        //先判断操作类型 10：上线  20：下线  30：控制
        this.messageEvent = messageEvent;
        if (this.messageEvent.getOperationType().equals("10") || this.messageEvent.getOperationType().equals("20")) {
            isExist(messageEvent.getApplianceId());
        } else if (this.messageEvent.getOperationType().equals("30")) {
            //加入
            // 111111：控制成功
            // 222222：控制失败
//            if (messageEvent.getParams().equals("111111")) {
                DeviceModel deviceModel = new DeviceModel();
                //基本项：device_id和appliance_id
                deviceModel.setDeviceId(AgentSharedPreferences.getMemberInfo(this).getMemberDeviceId());
                deviceModel.setApplianceId(messageEvent.getApplianceId());
                deviceModel.setOnlineStatus("10");
                deviceModel.setStatus(messageEvent.getStatus());
                NettyClient.getInstance().deviceStatusChange(deviceModel);
//            }else if(messageEvent.getParams().equals("222222")){
//
//            }
        }
    }

    public void createOnlineMessage(String applianceMasterId, String applianceId, String type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", UUIDUtil.get36UUID());
        jsonObject.put("messageType", "10");
        jsonObject.put("memberId", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("applianceMasterId", applianceMasterId);
        if (type.equals("10")) {
            jsonObject.put("messageTitle", "设备上线");
            jsonObject.put("messageContent", "设备(" + applianceId + ")已上线。");
        } else if (type.equals("20")) {
            jsonObject.put("messageTitle", "设备下线");
            jsonObject.put("messageContent", "设备(" + applianceId + ")已下线。");
        }
        jsonObject.put("messageRead", "0");
        HttpUtils.post(mBaseActivity, 1005, ServerConstants.ADD_MESSAGE, jsonObject.toString(), mBaseActivity);
    }
}
